/** 
 * FunctionDefineExpression.java
 * @author Lex
 * 2007-8-20 ����06:18:16
 */
package fun.parser.ast.node;

import fun.parser.EvaluationException;
import fun.parser.ast.node.base.Expression;
import fun.parser.lexer.Token;
import fun.symtable.SymbolTable;

/**
 * ������
 */
public class FunctionDefineExpression extends Expression {
    private VariableExpression[] args = null;
    private Expression expression = null;
    private boolean hasAddedToSymbolTable = false;

    public FunctionDefineExpression(Token name, VariableExpression[] args, Expression expression) {
	super(name);
	if (null == args)
	    args = new VariableExpression[0];
	this.args = args;
	this.expression = expression;
	Expression[] children = new Expression[args.length + 1];
	System.arraycopy(args, 0, children, 0, args.length);
	children[args.length] = expression;
	this.setChildren(children);
    }

    public VariableExpression[] getArguments() {
	return this.args;
    }

    public Expression getExpression() {
	return this.expression;
    }

    @Override
    public double getValue(SymbolTable symtable) throws EvaluationException {
	if (false == hasAddedToSymbolTable) {
	    String[] argNames = new String[this.args.length];
	    for (int i = 0; i < args.length; i++)
		argNames[i] = args[i].getVariableName();
	    symtable.setFunction(this.getToken().getImage(), argNames, this.expression);
	    hasAddedToSymbolTable = true;
	}
	return 0;
    }
}
